package org.blogwu.learn.multithread.chapter3.demo11.v1;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 自定义线程创建工厂
 *
 * @author hyf
 * @date 2018-10-04
 **/
public class Main implements Runnable {

    @Override
    public void run() {
        System.out.println(Thread.currentThread().getName() + "   " + Thread.currentThread().getId() + " start");
        try {
            Thread.sleep(200);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }


    public static void main(String[] args) throws InterruptedException {
        ArrayBlockingQueue arrayBlockingQueue = new ArrayBlockingQueue(100);
        ThreadPoolExecutor th = new ThreadPoolExecutor(10, 20, 5, TimeUnit.SECONDS, arrayBlockingQueue, new OwnThreadFactory());
        for (int i = 0; i < 120; i++) {
            th.submit(new Main());
        }
        Thread.sleep(10000);

    }

    static class OwnThreadFactory implements ThreadFactory {
        private static final AtomicInteger poolNumber = new AtomicInteger(1);
        private final ThreadGroup group;
        private final AtomicInteger threadNumber = new AtomicInteger(1);
        private final String namePrefix;

        OwnThreadFactory() {
            System.out.println("OwnThreadFactory create");
            SecurityManager s = System.getSecurityManager();
            group = (s != null) ? s.getThreadGroup() :
                    Thread.currentThread().getThreadGroup();
            namePrefix = "mySb pool-" +
                    poolNumber.getAndIncrement() +
                    "-thread-";
        }

        public Thread newThread(Runnable r) {
            System.out.println(r + " submit");
            Thread t = new Thread(group, r,
                    namePrefix + threadNumber.getAndIncrement(),
                    0);
            if (t.isDaemon())
                t.setDaemon(false);
            if (t.getPriority() != Thread.NORM_PRIORITY)
                t.setPriority(Thread.NORM_PRIORITY);
            return t;
        }
    }
}
